<template>
  <div v-loading="editLoading" class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
       <!-- <el-button icon="el-icon-back" @click="backHistory">{{ isAdd ? '新增' : '编辑' }}公告</el-button> -->
         <span style="line-height: 34px;font-size: 18px;font-weight: 500;" @click="backHistory"> {{ isAdd ? '新增' : '编辑' }}公告</span>
        <el-button :loading="loading" style="float: right;" type="primary" icon="el-icon-edit" @click="doSubmit">保存</el-button>
        <el-button  style="float: right;margin-right: 5px;" type="success" icon="el-icon-refresh-left" @click="backHistory">取消</el-button>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="公告名称:" prop="name">
              <el-input v-model="form.name" maxlength="20" placeholder="公告名称" style="width: 320px;"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="公告类型:" class="dd-label" prop="type">
              <el-select v-model="form.type" style="width: 330px" clearable filterable placeholder="公告类型">
                <el-option v-for="item in dicts" :key="item.id" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="公告状态:" class="dd-label" prop="status">
              <el-select v-model="form.status" style="width: 330px" clearable filterable placeholder="公告状态">
                <el-option v-for="item in statusList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div ref="editor" style="text-align:left;margin: 5px"/>
    </el-card>
    <div style="margin: 12px 5px;font-size: 16px;font-weight: bold;color: #696969">HTML渲染如下：</div>
    <div class="editor-content" v-html="form.content"/>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import E from 'wangeditor'
import { getToken } from '@/utils/auth'
import { add, edit, get } from '@/api/framework/notice/sysNotice'
import initDict from '@/mixins/initDict'

export default {
  mixins: [initDict],
  data() {
    return {
      headers: {
        'Authorization': 'Bearer ' + getToken()
      },
      isAdd: true,
      loading: false,
      editLoading: !this.isAdd,
      statusList:[{"id":0,"name":"未发布"},{"id":1,"name":"已发布"}],
      form: {
        id: this.$route.query.id,
        content: '',
        name: '',
        type: '',
        status: null
      },
      rules: {
        name: [
          { required: true, message: '请填写公告名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择公告类型', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择公告状态', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'imagesUploadApi'
    ])
  },
  created() {
    this.getDict('notice_type')
    if (this.$route.query.id) {
      this.isAdd = false
    } else {
      this.isAdd = true
      this.editLoading = false
    }
  },
  mounted() {
    var editor = new E(this.$refs.editor)
    editor.config.uploadImgShowBase64 = true // 使用 base64 保存图片

    //editor.customConfig.uploadImgHeaders = this.headers  //上传到服务器
    // 自定义文件名，不可修改，修改后会上传失败
    //editor.customConfig.uploadFileName = 'file'
    // URL
    // editor.customConfig.uploadImgServer = this.imagesUploadApi
    editor.config.onchange = (html) => {
      this.form.content = html
    }
    editor.create()
    if (!this.isAdd) {
      get(this.$route.query.id).then(data => {
        this.form = data
        editor.txt.html(this.form.content)
        this.editLoading = false
      }).catch(error => {
        console.log(error)
      })
    }
  },
  methods: {
    doSubmit() {
      this.loading = true
      if (this.isAdd) {
        this.doAdd()
      } else this.doEdit()
    },
    doAdd() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.content === '' || this.form.content==null) {
            this.$message({
              message: '请输入公告内容',
              type: 'warning'
            })
            this.loading = false
            return
          }
          add(this.form).then(res => {
            this.$notify({
              title: '添加成功',
              type: 'success',
              duration: 2500
            })
            this.loading = false
            this.backHistory()
          }).catch(err => {
            this.loading = false
            console.log(err)
          })
        }else{
          this.loading = false;
        }
      })
    },
    doEdit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          edit(this.form).then(res => {
            this.$notify({
              title: '修改成功',
              type: 'success',
              duration: 2500
            })
            this.loading = false
            this.backHistory()
          }).catch(err => {
            this.loading = false
            console.log(err)
          })
        }else{
          this.loading = false;
        }
      })
    },
    backHistory() {
      this.$router.back(-1)
    }
  }
}
</script>

<style scoped>
  .editor-content{
    padding-left: 5px;
  }
  .svg-icon{
    font-size: 30px ;
  }
</style>
